package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {

    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandByPageAndSort(Integer page, Integer rows, String sortBy, Boolean desc, String key) {

        // 开始分页
        PageHelper.startPage(page, rows);
        //过滤
        Example example = new Example(Brand.class);
        Example.Criteria criteria1 = example.createCriteria();
        Example.Criteria criteria2 = example.createCriteria();

        if (StringUtils.isNotBlank(key)) {
            criteria1.andLike("name", "%" + key + "%");
            criteria2.andEqualTo("letter", key);
        }
        if (StringUtils.isNotBlank(sortBy)) {
            example.setOrderByClause(sortBy + (desc ? " desc " : " asc "));
        }
        example.or(criteria2);

        // 查询
        Page<Brand> pageInfo = (Page<Brand>) brandMapper.selectByExample(example);

        // 返回结果
        return new PageResult<>(pageInfo.getTotal(), new Long(pageInfo.getPages()), pageInfo.getResult());


    }

    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        brandMapper.insertSelective(brand);
        //新增品牌和分类中间表
        for (Long cid : cids) {
            brandMapper.insertCategoryBrand(cid, brand.getId());
        }


    }

    @Transactional
    public void updateBrand(Brand brand, List<Long> cids) {
        brandMapper.updateByPrimaryKeySelective(brand);

        brandMapper.deleteCategoryBrand(brand.getId());

        for (Long cid : cids) {
            brandMapper.insertCategoryBrand(cid, brand.getId());
        }

    }

    public List<Brand> queryBrandByCategory(Long cid) {
        List<Brand> brandList = brandMapper.queryBrandByCategory(cid);
        return brandList;

    }

    public List<Brand> queryBrandByIds(List<Long> ids) {
        return this.brandMapper.selectByIdList(ids);
    }
}
